const express = require('express');
const router = express.Router();
const multer = require("multer")
const path = require("path");
const tencentcloud = require("tencentcloud-sdk-nodejs")
const CvmClient = tencentcloud.asr.v20190614.Client;

const clientConfig = {
	// 腾讯云认证信息
	credential: {
		secretId: "腾讯云id",
		secretKey: "腾讯云key",
	},
	region: "ap-shanghai",
	// 可选配置实例
	profile: {
		signMethod: "HmacSHA256", // 签名方法
		httpProfile: {
			endpoint: "asr.tencentcloudapi.com",
			reqMethod: "POST", // 请求方法
			reqTimeout: 60, // 请求超时时间，默认60s
		},
	},
}

var storage = multer.diskStorage({
	// 配置文件上传后存储的路径
	destination: function (req, file, cb) {
		// console.log(__dirname);  //获取当前文件在服务器上的完整目录 
		// console.log(__filename); //获取当前文件在服务器上的完整路径
		cb(null, path.join(__dirname, '../video'))
	},
	// 配置文件上传后存储的路径和文件名
	filename: function (req, file, cb) {
		var filename = Date.now() + path.extname(file.originalname)
		cb(null, filename)
	}
})
var upload = multer({ storage: storage })

router.post('/video', upload.single('video'), (req, res) => {
	// 通过client对象调用想要访问的接口，需要传入请求对象以及响应回调函数
	let url = '存储video地址+video文件名';// + req.file.filename;
	// obj配置项可参照官方文档，可以让前端发参数改变配置
	let obj = {
		'Url': url,
		"ChannelNum": 1,
		"EngineModelType": "16k_zh",
		"ResTextFormat": 2,
		"SourceType": 0
	}
	const client = new CvmClient(clientConfig)
	client.CreateRecTask(obj).then(
		(data) => {
			let poll = setInterval(() => {
				client.DescribeTaskStatus(data.Data).then(
					(data) => {
						console.log(data);
						if (data.Data.Status == 2) {
							res.json({
								code: 200,
								data: data.Data.Result
							})
							clearInterval(poll)
						}
					},
					(err) => {
						console.error("error", err);
						clearInterval(poll)
					}
				);
			}, 5000);
		},
		(err) => {
			console.error("error", err)
		}
	)
})

module.exports = router;
